<template>
  <view class="sentence">
    <view class="container">
      <view class="top">
        <view class="top">
          <view class="time">
            <text>计时：{{ minuteNumber }}分{{ secondNumber }}秒</text>
          </view>
          <view class="title">
            <view class="title_content">
              <text class="title_text">{{ bookName }}/{{ chapterName }}</text>
              <text class="title_tips" v-if="type === 1"
                >点击音频播放英文,然后按正确顺序点击英文使排序正确</text
              >
              <text class="title_tips" v-if="type === 2"
                >看下面中文按正确顺序点击英文使排序正确</text
              >
            </view>
          </view>
        </view>
      </view>
      <view class="icon" @click="play()">
        <image
          src="https://hengxiao-resource.oss-cn-hangzhou.aliyuncs.com/web/resources/images/app/horn2.png"
          mode="widthFix"
        ></image>
      </view>
      <view class="content">
        <view class="box">
          <template v-for="(item, index) in sentenceList">
            <view
              class="selected"
              v-if="index === currentSentenceIndex"
              :key="index"
            >
              <view
                class="selected_content"
                :class="{
                  active: answer.word,
                  error: item.selectList[i].isError,
                }"
                v-for="(answer, i) in item.answerList"
                :key="i"
                @click="checkWord(answer, i)"
              >
                <input type="button" :disabled="true" :value="answer.word" />
              </view>
            </view>
          </template>
          <template v-for="(item, index) in sentenceList">
            <view
              class="word"
              v-if="index === currentSentenceIndex"
              :key="item.id"
            >
              <view
                class="word_content"
                :class="{ select: item.selectList[i].selected }"
                v-for="(word, i) in item.randomWords"
                :key="i"
                @click="selectWord(word, i)"
              >
                <!-- <input type="button" :disabled="true" :value="word" /> -->
                <view>{{ word }}</view>
              </view>
            </view>
            <template
              v-if="index === currentSentenceIndex && item.isCorrect === true"
            >
              <view class="result" :key="'answer' + index">
                <view class="result_top">
                  <image
                    src="https://hengxiao-resource.oss-cn-hangzhou.aliyuncs.com/web/resources/images/app/correct.png"
                  ></image>
                  <text class="correct">答对了,正确答案：</text>
                </view>
                <view class="result_bottom">
                  {{ item.sentence }}
                </view>
              </view>
            </template>
            <template
              v-if="index === currentSentenceIndex && item.isCorrect === false"
            >
              <view class="result" :key="'answer' + index">
                <view class="result_top">
                  <image
                    src="https://hengxiao-resource.oss-cn-hangzhou.aliyuncs.com/web/resources/images/app/error.png"
                  ></image>
                  <text class="error">答错了,正确答案：</text>
                </view>
                <view class="result_bottom">
                  {{ item.sentence }}
                </view>
              </view>
            </template>
          </template>
        </view>
      </view>
      <view class="fixed">
        <view class="info">
          <view class="progress">
            <text>{{ currentSentenceNumber }}</text>
            <text>/{{ allSentenceNumber }}题目</text>
          </view>
        </view>
        <view class="button">
          <view
            class="button_content next"
            @click="prevQuestion()"
            v-if="currentSentenceIndex !== 0"
          >
            <text>上一题</text>
          </view>
          <view
            class="button_content next"
            @click="nextQuestion()"
            v-if="currentSentenceIndex !== sentenceList.length - 1"
          >
            <text>下一题</text>
          </view>
          <view
            class="button_content submit"
            :class="{
              disabled: isSee,
            }"
            @click="submit()"
            v-if="currentSentenceIndex === sentenceList.length - 1"
          >
            <text>提交</text>
          </view>
          <view
            class="button_content reselection"
            :class="{
              disabled: isSee,
            }"
            @click="reselection()"
          >
            <text>重选</text>
          </view>
        </view>
      </view>
    </view>
    <u-mask :show="isCompleted" :zoom="false">
      <view class="popup_container" v-if="isPass">
        <view class="popup_image">
          <image
            src="https://hengxiao-resource.oss-cn-hangzhou.aliyuncs.com/web/resources/images/app/laugh.png"
            mode="widthFix"
          ></image>
        </view>
        <view class="popup_text">
          <text>{{ score }}</text>
          <text>分</text>
        </view>
        <view class="popup_tips">
          恭喜你！ 已结束本轮学习，即将开启下一轮！
        </view>
        <view class="popup_button">
          <view class="popup_button_content active" @click="seeAll()"
            ><text>查看全部</text></view
          >
          <view
            class="popup_button_content"
            @click="seeError()"
            v-if="errorsentenceList.length > 0"
          >
            <text>仅看错题</text>
          </view>
          <view class="popup_button_content" @click="handleBack()"
            ><text>返回</text></view
          >
        </view>
      </view>
      <view class="popup_container" v-else>
        <view class="popup_image">
          <image
            src="https://hengxiao-resource.oss-cn-hangzhou.aliyuncs.com/web/resources/images/app/cry.png"
            mode="widthFix"
          ></image>
        </view>
        <view class="popup_text">
          <text>{{ score }}</text>
          <text>分</text>
        </view>
        <view class="popup_tips"> 很遗憾 ! 未通关 , 解锁失败。 </view>
        <view class="popup_button">
          <view class="popup_button_content active" @click="seeAll()">
            <text>查看全部</text>
          </view>
          <view class="popup_button_content" @click="seeError()">
            <text>仅看错题</text>
          </view>
        </view>
      </view>
    </u-mask>
  </view>
</template>

<script>
export default {
  components: {},
  filters: {
    typeFilter(type) {
      return type === 1 ? "句子听选" : "句子拼写";
    },
  },
  props: {
    type: {
      type: Number,
      default: 1,
    },
    sentenceList: {
      type: Array,
      default: () => [],
    },
    bookInfo: {
      type: Object,
      default: null,
    },
  },
  computed: {
    currentWidth() {
      return parseInt(
        (this.currentSentenceNumber / this.allSentenceNumber) * 100
      );
    },
  },
  created() {
    this.init();
  },
  mounted() {
    this.time();
  },
  data() {
    return {
      bookName: "",
      chapterName: "",
      currentSentenceIndex: 0,
      currentSentenceNumber: 1,
      allSentenceNumber: 1,
      answerList: [],
      allScore: 100,
      passScore: 80,
      singleScore: 0,
      score: 0,
      correctNumber: 0,
      correctsentenceList: [],
      errorNumber: 0,
      errorsentenceList: [],
      isCompleted: false,
      minute: 0,
      minuteNumber: "00",
      second: 0,
      secondNumber: "00",
      timerId: null,
      audio: null,
      isPlaying: false,
      isPass: false,
      isSee: false,
    };
  },
  methods: {
    init() {
      this.bookName = this.bookInfo.bookEdition + this.bookInfo.bookYear;
      this.chapterName = this.bookInfo.shortName;
      this.allSentenceNumber = this.sentenceList.length;
      this.singleScore = this.allScore / this.allSentenceNumber;
      this.initOptions();
      this.play();
    },
    initOptions() {
      this.sentenceList.forEach((item) => {
        let randomWords = item.randomWords;
        let wordslist = this.handlerandomWords(randomWords);
        this.$set(item, "answerList", wordslist.answerList);
        this.$set(item, "selectList", wordslist.selectList);
      });
    },
    handlerandomWords(list) {
      let answerList = [];
      let selectList = [];
      let reg = /\p{P}/u;
      for (let i = 0; i < list.length; i++) {
        if (reg.test(list[i])) {
          answerList.push({ word: list[i], index: i });
          selectList.push({ selected: true });
        } else {
          answerList.push({ word: "", index: -1 });
          selectList.push({ selected: false });
        }
      }
      return {
        answerList: answerList,
        selectList: selectList,
      };
    },
    selectWord(word, i) {
      if (this.sentenceList[this.currentSentenceIndex].isCorrect !== undefined)
        return;
      if (this.isSee) return;
      let isSelected =
        this.sentenceList[this.currentSentenceIndex].selectList[i].selected;
      if (isSelected) return;
      let answerList = this.sentenceList[this.currentSentenceIndex].answerList;
      answerList.some((item, index) => {
        if (item.word === "") {
          answerList.splice(index, 1, { word: word, index: i });
          return true;
        }
      });
      this.sentenceList[this.currentSentenceIndex].selectList[
        i
      ].selected = true;
    },
    checkWord(answer, i) {
      if (this.sentenceList[this.currentSentenceIndex].isCorrect !== undefined)
        return;
      if (this.isSee) return;
      if (answer.word === "") return;
      this.sentenceList[this.currentSentenceIndex].answerList[i].word = "";
      this.sentenceList[this.currentSentenceIndex].selectList[
        answer.index
      ].selected = false;
    },
    prevQuestion() {
      this.currentSentenceIndex -= 1;
      this.currentSentenceNumber -= 1;
      if (this.isPlaying) {
        this.audio.pause();
        this.isPlaying = false;
        this.play();
      } else {
        this.play();
      }
    },
    nextQuestion() {
      if (!this.checkRightAndWrong()) {
        this.$set(
          this.sentenceList[this.currentSentenceIndex],
          "isCorrect",
          true
        );
        this.correctsentenceList.push(
          this.sentenceList[this.currentSentenceIndex]
        );
      } else {
        this.$set(
          this.sentenceList[this.currentSentenceIndex],
          "isCorrect",
          false
        );
        this.errorsentenceList.push(
          this.sentenceList[this.currentSentenceIndex]
        );
        let sentenceList = this.sentenceList[this.currentSentenceIndex];
        for (let i = 0; i < sentenceList.answerList.length; i++) {
          if (
            sentenceList.answerList[i].word !== sentenceList.sentenceWords[i]
          ) {
            this.$set(sentenceList.selectList[i], "isError", true);
          } else {
            this.$set(sentenceList.selectList[i], "isError", false);
          }
        }
      }
      this.currentSentenceIndex += 1;
      this.currentSentenceNumber += 1;
      if (this.isPlaying) {
        this.audio.pause();
        this.isPlaying = false;
        this.play();
      } else {
        this.play();
      }
    },
    reselection() {
      if (this.isSee) return;
      let isCorrect = this.sentenceList[this.currentSentenceIndex].isCorrect;
      if (isCorrect !== undefined) {
        this.$set(
          this.sentenceList[this.currentSentenceIndex],
          "isCorrect",
          undefined
        );
      }
      let randomWords =
        this.sentenceList[this.currentSentenceIndex].randomWords;
      let wordslist = this.handlerandomWords(randomWords);
      this.$set(
        this.sentenceList[this.currentSentenceIndex],
        "answerList",
        wordslist.answerList
      );
      this.$set(
        this.sentenceList[this.currentSentenceIndex],
        "selectList",
        wordslist.selectList
      );
    },
    submit() {
      if (this.isSee) return;
      if (!this.checkRightAndWrong()) {
        this.$set(
          this.sentenceList[this.currentSentenceIndex],
          "isCorrect",
          true
        );
        this.correctsentenceList.push(
          this.sentenceList[this.currentSentenceIndex]
        );
      } else {
        this.$set(
          this.sentenceList[this.currentSentenceIndex],
          "isCorrect",
          false
        );
        this.errorsentenceList.push(
          this.sentenceList[this.currentSentenceIndex]
        );
        let sentenceList = this.sentenceList[this.currentSentenceIndex];
        for (let i = 0; i < sentenceList.answerList.length; i++) {
          if (
            sentenceList.answerList[i].word !== sentenceList.sentenceWords[i]
          ) {
            this.$set(sentenceList.selectList[i], "isError", true);
          } else {
            this.$set(sentenceList.selectList[i], "isError", false);
          }
        }
      }
      this.sentenceList.forEach((item) => {
        if (item.isCorrect) {
          this.correctNumber++;
        }
      });
      this.score = parseInt(this.correctNumber * this.singleScore);
      this.isPass = this.score >= this.passScore ? true : false;
      clearInterval(this.timerId);
      this.saveRecord();
      this.isCompleted = true;
    },
    checkRightAndWrong() {
      let answerList = this.sentenceList[this.currentSentenceIndex].answerList;
      let sentenceWords =
        this.sentenceList[this.currentSentenceIndex].sentenceWords;
      return answerList.some((item, index) => {
        if (item.word !== sentenceWords[index]) {
          return true;
        }
      });
    },
    seeAll() {
      this.initListeningSentence();
      this.isCompleted = false;
      this.isSee = true;
    },
    seeError() {
      this.sentenceList = this.errorsentenceList;
      this.initListeningSentence();
      this.isCompleted = false;
      this.isSee = true;
    },
    initListeningSentence() {
      this.correctsentenceList = [];
      this.errorsentenceList = [];
      this.currentSentenceIndex = 0;
      this.currentSentenceNumber = 1;
      this.correctNumber = 0;
      this.errorNumber = 0;
    },
    play() {
      if (this.isPlaying) return;
      this.audio = uni.createInnerAudioContext();
      this.audio.src = this.sentenceList[this.currentSentenceIndex].audio;
      this.audio.play();
      this.audio.onEnded(() => {
        this.isPlaying = false;
      });
      this.audio.onError(() => {
        this.isPlaying = false;
      });
      this.isPlaying = true;
    },
    time() {
      this.timerId = setInterval(() => {
        this.second++;
        if (this.second > 59) {
          this.second = 0;
          this.minute++;
        }
        if (this.second < 10) {
          this.secondNumber = this.second.toString().padStart(2, "0");
        } else {
          this.secondNumber = this.second.toString();
        }
        if (this.minute < 10) {
          this.minuteNumber = this.minute.toString().padStart(2, "0");
        } else {
          this.minuteNumber = this.minute.toString();
        }
      }, 1000);
    },
    saveRecord() {
      this.$emit("save", 85);
    },
    handleBack() {
      this.$emit("back");
    },
  },
};
</script>

<style lang="scss" scoped>
@import "./SentenceTest.scss";
</style>

